package com.jaxb;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class TestXPath {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><requestData><author><address>address1</address></author><name>name1</name></requestData>";

        // 1 Doc Builder Factory
        final DocumentBuilderFactory domFactory =
        DocumentBuilderFactory.newInstance();

        domFactory.setNamespaceAware(true); // never forget this!
        // 2 Doc Builder
        final DocumentBuilder builder = domFactory.newDocumentBuilder();

        // 3 Doc
        final Document document = builder.parse(String2InputStream(xml));
        
     // 4 XPath Factory
        final XPathFactory factory = XPathFactory.newInstance();

        // 5 XPath
        final XPath xpath = factory.newXPath();

        //xpath.setNamespaceContext(nsContext);
        // 6 Expression
        final XPathExpression expr = xpath.compile("//requestData");
        // 7 NodeList(NODESET)
        
        Node root = ((NodeList)expr.evaluate(document, XPathConstants.NODESET)).item(0);

        if(root.hasChildNodes()) {
        	NodeList nodeList = root.getChildNodes();
        	for(int i = 0; i < nodeList.getLength(); i++) {
        		Node child = nodeList.item(i);
        		if(child.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
            		System.out.print("node" + i + ":");
            		System.out.print("node name is:" + child.getNodeName());
            		System.out.print(" ");
            		String start = "<"+child.getNodeName();
            		String end = "</"+child.getNodeName()+">";
            		System.out.print("node value is:" + xml.substring(xml.indexOf(start),xml.lastIndexOf(end)) + end);
            		System.out.println("");
            	} else {
            		System.out.print("node" + i + ":");
            		System.out.print("node name is:" + child.getNodeName());
            		System.out.print(" ");
            		//System.out.print("node value is:" + child.getTextContent());
            		System.out.println("");
            	}
        	}
        }
        
        

        
	}
	
	private static InputStream String2InputStream(String str) {
		return new ByteArrayInputStream(str.getBytes());


	}

}
